package netengine;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

import main.Game;

import org.apache.log4j.Logger;

import player.LoginManager;
import player.Player;

public class NetAcceptHandler 
{
	static Logger logger = Logger.getLogger(Game.class);
	
	public NetAcceptHandler(ServerSocketChannel socketChannel)
	{ 
		selectionKey        = null;
		serverSocketChannel = socketChannel;
	}
	
	public SocketChannel handleAccept()
	{
		SocketChannel channel = null;
		
		try
		{
			channel = serverSocketChannel.accept();
			channel.configureBlocking(false);
			
			Socket socket            = channel.socket();
			int    sendBufferSize    = socket.getSendBufferSize();
			int    receiveBufferSize = socket.getReceiveBufferSize();
			InetAddress inetAddress  = socket.getInetAddress();
			
			logger.info("accept new connection on local port " 
			            + serverSocketChannel.socket().getLocalPort() 
					    + ": remote ip = " + inetAddress.getHostAddress() 
					    + ", remote port = " + socket.getPort() 
					    + ", send buffer size = " + sendBufferSize
					    + ", receive buffer size = " + receiveBufferSize + ".");
			
			NetSocketHandler socketHandler = new NetSocketHandler(channel); 
			SelectionKey key = NetEngine.getInstance().registerHandler(channel, SelectionKey.OP_READ, socketHandler);
			socketHandler.setSelectionkey(key);
			
			Player player = new Player(socketHandler);
			LoginManager.getInstance().addPlayer(player);
		}
		catch(IOException exception)
		{
			logger.error("Exception: ", exception);
		} 
		
		return null;
	}
	 
	public void setSelctionKey(SelectionKey key)
	{
		selectionKey = key;
	}
	
	private SelectionKey        selectionKey;
	private ServerSocketChannel serverSocketChannel;
}
